#!/usr/bin/python -S
"""
timer.py

Function names taken from Node.js
"""

__author__ = 'Andy Chu'


import time

import ioloop
import log


def set_timeout(deadline, callback, loop=None):
  now = time.time()
  loop = loop or ioloop.instance()
  handle = loop.add_timeout(now + deadline, callback)
  log.trace('Added timeout %s', handle)
  return handle


def clear_timeout(timeout, loop=None):
  loop = loop or ioloop.instance()
  loop.remove_timeout(timeout)


def callback_with_timeout(callback, deadline, timeout_callback, loop=None):
  """
  Returns another callback.

  If the event to trigger callback doesn't happen within a certain amount of
  time, the timeout_callback is called.

  If it happens in time, the normal callback is called, AND the timeout is
  removed.  Automatically removing the timeout is the convenience behind this
  function.
  """
  loop = loop or ioloop.instance()

  timeout = set_timeout(deadline, timeout_callback, loop=loop)
  #print '@@@@@@@@@@@@@@ timeout', timeout
  def normal_cb(*args, **kwargs):
    # Cancel the timeout and call the callback
    print 'CANCELING timeout', timeout
    loop.remove_timeout(timeout)
    callback(*args, **kwargs)

  return normal_cb

